import React from "react";
import routes from "../router/routes";
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  PieChartOutlined,
  DesktopOutlined
} from "@ant-design/icons";
import { Menu, Button } from "antd";
import { Link } from "react-router-dom";
const { SubMenu } = Menu;
class App extends React.Component {
  constructor(props) {
    super(props);
    let menuData = routes.filter(item => {
      if (item.routes && routes.length > 0) {
        item.routes = item.routes.filter(items => items.icon);
      }
      return item.icon;
    });
    this.state = {
      collapsed: false,
      menuData: menuData
    };
  }
  toggleCollapsed = () => {
    this.setState({
      collapsed: !this.state.collapsed
    });
  };
  render() {
    const menuData = this.state.menuData;
    let defaultSelectedKeys = [];
    let defaultOpenKeys = [];
    let locationPath = this.props.location.pathname;
    let matchPath = this.props.match.path;
    if (locationPath === matchPath) {
      defaultOpenKeys = [matchPath];
    } else if (locationPath.indexOf(matchPath) >= 0) {
      defaultOpenKeys = [matchPath];
      defaultSelectedKeys = [locationPath];
    }
    // console.log(defaultOpenKeys, defaultSelectedKeys);
    return (
      <div className="siderBar">
        <Button
          type="primary"
          onClick={this.toggleCollapsed}
          style={{
            marginBottom: 16
          }}
        >
          {React.createElement(
            this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined
          )}
        </Button>
        <Menu
          defaultSelectedKeys={defaultSelectedKeys}
          defaultOpenKeys={defaultOpenKeys}
          mode="inline"
          theme="dark"
          inlineCollapsed={this.state.collapsed}
        >
          {menuData.map((item, i) => {
            if (item.routes && item.routes.length > 0) {
              return (
                <SubMenu
                  key={item.path}
                  title={
                    <span>
                      <PieChartOutlined />
                      {item.name}
                    </span>
                  }
                >
                  {item.routes.map((items, j) => {
                    return (
                      <Menu.Item key={items.path}>
                        <Link to={items.path}> {items.name} </Link>
                      </Menu.Item>
                    );
                  })}
                </SubMenu>
              );
            } else {
              return (
                <Menu.Item key={item.path}>
                  <DesktopOutlined />
                  <span>
                    <Link to={item.path}> {item.name} </Link>
                  </span>
                </Menu.Item>
              );
            }
          })}
        </Menu>
      </div>
    );
  }
}
export default App;
